<template>
  <div class="question-box">
    <div class="question-main">
      <!-- 答题卡 -->
      <div class="question-sub-box" v-if="card">
        <!-- <div class="s-title">答题卡</div> -->
        <slot name="card-title"></slot>
        <div class="sub-box_con">
          <ul class="ul-box">
            <li v-for="(item, index) in questionData" :key="index" :class="{ selected: isCheck(item.checkIds) }">
              <a :href="`#formItem${index}`">{{ index + 1 }}</a>
            </li>
          </ul>
          <div class="total">
            已完成<span> {{ selectQuestion }} </span>道题，共<span> {{ questionData.length }} </span>道题
          </div>
          <slot name="card-btn" class="submit-que"></slot>
          <!-- <el-button type="primary" class="submit-que" @click="subQuestion">提交问卷</el-button> -->
        </div>
      </div>
      <!-- 问卷内容 -->
      <div class="question-con">
        <slot name="title" class="title"></slot>
        <!-- <div class="title">{{ data.domain }}（{{ data.domainName }}） 审计指标设定（调查问卷）</div> -->
        <el-form
          :model="ruleForm"
          label-position="top"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="ruleForm"
        >
          <span v-for="(item, index) in questionData" :key="index">
            <!-- <span class="sign">{{ index + 1 }}.</span> -->
            <el-form-item :prop="item.sceneId" v-if="item.options === 'checkbox'" :id="`formItem${index}`">
              <span slot="label">{{ index + 1 }}、{{ item.question }}</span>
              <el-checkbox-group
                :disabled="disabled"
                v-model="ruleForm[item.sceneId]"
                @change="checkboxChange(item, 'checkbox', $event)"
              >
                <el-tooltip
                  class="item"
                  v-for="(check, i) in item.optionNames"
                  :key="i"
                  effect="dark"
                  :content="`场景备注：${check.remark}`"
                  placement="top"
                >
                  <el-checkbox :disabled="checkDis(item, check)" :label="check.id"
                    >{{ check.optionName
                    }}<i
                      v-if="check.autoCheckedFlag == 1 && !item.checkIds.includes(check.id)"
                      style="margin-left: 2px; font-size: 1rem; color: #f56c6c"
                      class="el-icon-warning-outline"
                    ></i>
                  </el-checkbox>
                  <!-- -->
                </el-tooltip>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item :prop="item.sceneId" v-if="item.options === 'radio'" :id="`formItem${index}`">
              <span slot="label">{{ index + 1 }}、{{ item.question }}</span>
              <el-radio-group
                :disabled="disabled"
                v-model="ruleForm[item.sceneId]"
                @change="radioChange(item, 'radio')"
              >
                <el-tooltip
                  class="item"
                  v-for="(check, i) in item.optionNames"
                  :key="i"
                  effect="dark"
                  :content="`场景备注：${check.remark}`"
                  placement="top"
                >
                  <el-radio :label="check.id"
                    >{{ check.optionName
                    }}<i
                      v-if="check.autoCheckedFlag == 1 && !item.checkIds.includes(check.id)"
                      style="margin-left: 2px; font-size: 1rem; color: #f56c6c"
                      class="el-icon-warning-outline"
                    ></i
                  ></el-radio>
                </el-tooltip>
              </el-radio-group>
            </el-form-item>
          </span>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "secQuestion",
  props: {
    data: Array,
    customRule: Object | Boolean,
    answerCard: Object,
    card: Boolean,
    disabled: Boolean,
  },
  components: {},
  data() {
    return {
      questionData: [], //调查问卷界面展示题目的数据
      ruleForm: {},
      rules: {},
    };
  },
  computed: {
    /**
     * @函数功能:在答题卡 实现已完成多少道题的联动
     * @参数输入:
     * @函数返回:
     */
    selectQuestion() {
      let selectNum = 0;
      this.questionData.forEach((item) => {
        if (this.isCheck(item.checkIds)) {
          selectNum++;
        }
      });
      return selectNum;
    },
  },
  mounted() {},
  methods: {
    //checkbox 复选框 失效的处理
    checkDis(item, checkObj) {
      if (item.checkIds.length > 0) {
        let { optionNames } = item;
        let isMutexObj = optionNames.find((item) => item.isMutex == 1);
        if (!isMutexObj) return false;
        //如果选择了(isMutex=1)互斥的那个选项。(其他不带isMutex字段的就要置灰)
        if (item.checkIds.includes(isMutexObj.id)) {
          return checkObj.id != isMutexObj.id && true;
        } else {
          return checkObj.id == isMutexObj.id && true;
        }
      }
    },
    checkboxChange(item, type, $event) {
      this.setQuestionData(item, type);
    },
    radioChange(item, type) {
      this.setQuestionData(item, type);
    },
    /**
     * @函数功能:把选中的值 赋值给questionData 里面的 check字段里面
     * @参数输入:
     * @函数返回:
     */
    setQuestionData({ sceneId, checkIds, optionNames }, type) {
      console.log(sceneId);
      console.log(checkIds);
      console.log(this.ruleForm);
      //@wiki http://wiki.intra.xiaojukeji.com/pages/viewpage.action?pageId=854941566
      let sign = false; //根据资产标签：回填“审计中心-问卷”中的场景，支持用户取消勾选；取消时提醒“系统检测存在该场景，确认取消么？”
      let oldCheckIdsLen = checkIds.length;
      let newCheckIdsLen = this.ruleForm[sceneId].length;
      if (type == "radio" && oldCheckIdsLen > 0) {
        optionNames.forEach((item) => {
          if (item.autoCheckedFlag == 1 && checkIds[0] == item.id) {
            sign = true;
          }
        });
      } else {
        if (newCheckIdsLen < oldCheckIdsLen) {
          let cancelId = [];
          checkIds.forEach((item) => {
            if (!this.ruleForm[sceneId].includes(item)) {
              cancelId.push(item);
            }
          });
          optionNames.forEach((item) => {
            if (item.autoCheckedFlag == 1 && cancelId[0] == item.id) {
              sign = true;
            }
          });
        }
      }

      if (sign) {
        this.utils.$confirm(
          { content: "系统检测存在该场景，确认取消吗？" },
          () => {
            //点击确认
            this.questionDataHandle(sceneId);
          },
          () => {
            //点击取消
            this.ruleForm[sceneId] = type == "radio" ? checkIds[0] : checkIds;
            console.log(this.ruleForm);
          },
        );
      } else {
        this.questionDataHandle(sceneId);
      }
    },
    questionDataHandle(sceneId) {
      this.questionData.forEach((item, index) => {
        //兼容之前添加了（序号、） 现在需要去除 实现传给后台的时候question也不带着（序号、） 现在是直接在html中加这个序号、了
        // item.question = item.question.slice(item.question.indexOf("、") + 1);
        if (item.sceneId == sceneId) {
          if (item.options === "radio") {
            item.checkIds = [];
            item["checkIds"].push(this.ruleForm[sceneId]);
          } else if (item.options === "checkbox") {
            item["checkIds"] = this.ruleForm[sceneId];
          }
        }
      });
    },
    /**
     * @函数功能:根据复选框和单选框 是否选中
     * @参数输入:checkIds(里面放的是optionNames.id的值) 复选框是数组 单选框是字符串
     * @函数返回:选中返回true 否则false
     */
    isCheck(checkIds) {
      if (Array.isArray(checkIds)) {
        return checkIds.length > 0 || false;
      }
      return checkIds || false;
    },
    init() {
      let form = {}; //解决vue 不触发视图更新 把一些对象先赋值到这个对象上，然后在把整个对象赋值给ruleForm
      let rules = {};
      //有标题但是没有选项的筛选掉
      this.questionData = this.questionData.filter((item) => {
        return item.optionNames.length > 0;
      });
      this.questionData.forEach((item, index) => {
        if (item.options === "checkbox") {
          form[item.sceneId] = item.checkIds || [];
        } else if (item.options === "radio") {
          //由于checkIds 都是数组，radio类型下需要转化成字符串才可以
          form[item.sceneId] = item.checkIds.length > 0 ? item.checkIds[0] : "";
        }
        rules[item.sceneId] = [{ required: true, message: "请选择", trigger: "blur" }];
      });
      this.ruleForm = form;
      if (typeof this.customRule === "boolean") {
        this.customRule && (this.rules = rules);
        !this.customRule && (this.rules = {});
        return;
      }
      this.rules = this.customRule;
    },
    //提交问卷
    submit() {
      let sign = true;
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          this.$emit("submit", this.questionData);
          sign = this.questionData;
        } else {
          this.message.error({ message: "有必选项没选择" });
          sign = false;
        }
      });
      return sign;
    },
  },
  watch: {
    data: {
      handler(newVal) {
        this.questionData = newVal;
        this.init();
      },
      // deep: true,
      immediate: true,
    },
  },
};
</script>
<style lang="scss" scoped>
//@import url(); 引入公共css类
.sign {
  font-size: 24px;
  color: $menuActiveText;
  float: left;
  line-height: 35px;
  margin-right: 10px;
  // font-weight: 600;
}
.question-main {
  width: 1100px;
  margin: 10px auto;
  position: relative;
}
.ruleForm {
  margin: 20px;
  padding-bottom: 15px;
  ::v-deep .el-form-item__label {
    font-size: 15px;
    padding-bottom: 0;
  }
  ::v-deep .el-checkbox-group,
  ::v-deep .el-radio-group,
  ::v-deep .el-form-item__error {
    margin-left: 40px;
  }
}
.question-sub-box {
  position: fixed;
  right: 50%;
  top: 100px;
  width: 310px;
  // height: 250px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  background: #fff;
  border-radius: 4px;
  margin-right: -560px;
}
.question-con {
  width: 760px;
  background: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
.sub-box_con {
  margin: 5px 15px 20px;
}
.sub-question_btn {
  margin: 10px;
  text-align: center;
}
.ul-box {
  overflow: hidden;
  margin: 10px 0;
  padding: 0;
  border-bottom: 1px dashed #eee;
  li {
    font-size: 12px;
    float: left;
    background: #ffffff;
    float: left;
    width: 22px;
    height: 22px;
    line-height: 22px;
    border: #cccccc 1px solid;
    border-radius: 3px;
    cursor: pointer;
    text-align: center;
    color: #666666;
    margin: 0px 6px 6px 0px;
    &.selected {
      background: $menuActiveText;
      color: #fff;
      border: 0;
    }
  }
}
.total {
  margin-bottom: 10px;
  span {
    color: red;
  }
}
.submit-que {
  width: 100%;
  border-radius: 0;
  font-size: 16px;
}
</style>
